import type { EChartsOption } from "echarts";
import { getFabConsume, getFabEmissionAndRecovery, getFabMachineEmissionAndRecovery, getFabElectricityConsume } from "@/api/modules/fab";
import { isActuallyEmpty, getParams } from "./lineEchartsHooks";
import { useLabelLayoutBarChartFn } from "@/hooks/useEcharts";
import type { SubjectType } from "@/utils/types";

/**
 * @description: 柱状图配置
 * @param {SubjectType} subject
 * @param {Boolean} flag           是否有回收或者排放（水课、机械课），默认为false
 * @param {String} unit            单位
 * @param {Array} xAxisData        横坐标
 * @param {Array} specData         SPEC目标值
 * @param {Array} usedData         实际值
 * @param {Array} noUsedData       余量
 * @param {Array} excessUsedData   超额
 * @param {Array} recoveryData     回收或者排放
 * @return {*}
 */
const labelLayoutBarChartFn = (
  subject: SubjectType,
  flag = false,
  unit: string,
  xAxisData?: Array<string>,
  specData?: Array<number>,
  usedData?: Array<number>,
  noUsedData?: Array<number>,
  excessUsedData?: Array<number>,
  actuallyUsedData?: Array<any>,
  recoveryData?: Array<number>
): CommonEcharts.CommonEchartsOption => {
  const label = {
    show: true,
    formatter: function (params) {
      if (params.value === 0) {
        return "";
      } else {
        return params.value;
      }
    }
  };
  const emphasis = {
    focus: "series"
  };
  const legend = {
    show: true,
    selectedMode: false,
    data: [
      {
        name: "SPEC目标值",
        itemStyle: {
          color: "#F4616F"
        }
      },
      {
        name: "实际用量",
        itemStyle: {
          color: "#3B82F6"
        }
      },
      {
        name: "余量",
        itemStyle: {
          color: "#DCE4F1"
        }
      },
      {
        name: "超额",
        itemStyle: {
          color: "#FFC200"
        }
      },
      {
        name: "回收量",
        itemStyle: {
          color: "#28D892"
        }
      },
      {
        name: "大气排放",
        itemStyle: {
          color: "#28D892"
        }
      }
    ]
  };
  const tooltip: any = {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    },
    formatter: function (params) {
      let str = "";
      params.forEach((item, index) => {
        let { marker, seriesName, data } = item;
        let itemDom = "";
        if (index === 1 && params[3].data > 0) {
          const color = "#3B82F6";
          marker = `<span style=\"display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};\"></span>`;
          itemDom = `${marker}${seriesName} : ${params[0].data + params[3].data || "--"}`;
        } else {
          itemDom = `${marker}${seriesName} : ${data || "--"}`;
        }
        str += itemDom;
        str += index === params.length - 1 || !itemDom ? "" : "<br/>";
      });
      return str;
    }
  };
  const commonOptions: EChartsOption = {
    title: {
      subtext: `单位 / ${unit}`,
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    },
    legend,
    tooltip,
    grid: {
      left: 0,
      right: 0,
      top: 46,
      bottom: 0,
      containLabel: true
    },

    xAxis: [
      {
        type: "category",
        data: xAxisData
      }
    ],
    yAxis: [
      {
        type: "value",
        boundaryGap: ["0", "1%"]
      }
    ]
  };
  const series: Array<any> = [
    {
      name: "SPEC目标值",
      type: "bar",
      label,
      emphasis,
      data: specData,
      itemStyle: {
        color: "#F4616F"
      }
    },
    {
      name: "实际用量",
      type: "bar",
      stack: "Ad",
      label,
      emphasis,
      data: usedData,
      itemStyle: {
        color: function (params) {
          const { dataIndex } = params;
          const flag = actuallyUsedData.find(item => item.coord[0] === dataIndex);
          return flag ? "#F4616F" : "#3B82F6";
        }
      }
    },
    {
      name: "余量",
      type: "bar",
      stack: "Ad",
      label,
      emphasis,
      data: noUsedData,
      itemStyle: {
        color: "#DCE4F1"
      }
    },
    {
      name: "超额",
      type: "bar",
      stack: "Ad",
      label,
      emphasis,
      data: excessUsedData,
      itemStyle: {
        color: "#FFC200"
      },
      markPoint: {
        symbol: "diamond",
        symbolSize: 20,
        symbolRotate: 180,
        symbolOffset: [0, -16],
        data: actuallyUsedData,
        label: {
          show: true,
          position: "top",
          color: "#fff",
          backgroundColor: "#3B82F6",
          padding: 6,
          borderRadius: 6,
          distance: -10,
          formatter: function (params) {
            const {
              data: { coord }
            } = params;
            return `实际：${coord[1]}`;
          }
        },
        itemStyle: {
          color: "#3B82F6"
        }
      }
    }
  ];
  if (flag) {
    const name = subject === "WATER" ? "回收量" : subject === "MACHINE" ? "大气排放" : "";
    const itemStyle = {
      color: "#28D892"
    };
    const o = {
      name,
      type: "bar",
      label,
      emphasis,
      data: recoveryData,
      itemStyle
    };

    series.push(o);
  }
  const options: EChartsOption = { ...commonOptions, series };
  return options;
};

/**
 * @description: 格式化消耗数据（气化课、水课）
 * @param {Array} res
 * @return {*}
 */
const formatConsumeGWData = (res: Array<any>) => {
  const xAxisData = [];
  const specData = [];
  const usedData = [];
  const noUsedData = [];
  const excessUsedData = [];
  const actuallyUsedData = [];
  res.forEach((item, index) => {
    const { consumeName, specNum, usedNum, noUsedNum, excessUsed } = item;
    xAxisData.push(consumeName);
    specData.push(specNum);
    if (usedNum !== null && specNum !== null) {
      if (usedNum > specNum) {
        usedData.push(specNum);
        actuallyUsedData.push({ coord: [index, usedNum] });
      } else {
        usedData.push(usedNum);
      }
    } else {
      usedData.push(usedNum);
    }
    noUsedData.push(noUsedNum);
    excessUsedData.push(excessUsed);
  });
  return {
    xAxisData,
    specData,
    usedData,
    noUsedData,
    excessUsedData,
    actuallyUsedData
  };
};

/**
 * @description: 格式化排放数据（气化课、水课、机械课）
 * @param {Array} res
 * @return {*}
 */
const formatEmissionAndRecoveryGWMData = (res: Array<any>) => {
  const xAxisData = [];
  const specData = [];
  const usedData = [];
  const noUsedData = [];
  const excessUsedData = [];
  const actuallyUsedData = [];
  const recoveryData = [];
  res.forEach((item, index) => {
    const { emissionName, specNum, usedNum, noUsedNum, excessUsed, recoveryNum } = item;
    xAxisData.push(emissionName);
    specData.push(specNum);
    if (usedNum !== null && specNum !== null) {
      if (usedNum > specNum) {
        usedData.push(specNum);
        actuallyUsedData.push({ coord: [index, usedNum] });
      } else {
        usedData.push(usedNum);
      }
    } else {
      usedData.push(usedNum);
    }
    noUsedData.push(noUsedNum);
    excessUsedData.push(excessUsed);
    recoveryData.push(recoveryNum);
  });
  return {
    xAxisData,
    specData,
    usedData,
    noUsedData,
    excessUsedData,
    actuallyUsedData,
    recoveryData
  };
};

const formatElectricityConsumeData = (res: Array<any>) => {
  if (!res?.length) return null;
  const xAxisData = res.map(item => item.dayStr);
  const data = res.map(item => item.value);
  return { xAxisData, data };
};

/**
 * @description: 获取消耗echarts配置（气化课、水课）
 * @param {SubjectType} subject
 * @param {string} unit
 * @return {*}
 */
export const useLabelLayoutConsumeGWFn = async (subject: SubjectType, unit: string): Promise<CommonEcharts.CommonEchartsOption> => {
  const params = getParams(subject);
  const res = await getFabConsume(params);
  if (!res?.length) return null;
  const { xAxisData, specData, usedData, noUsedData, excessUsedData, actuallyUsedData } = formatConsumeGWData(res);
  if (
    isActuallyEmpty(xAxisData) ||
    (isActuallyEmpty(specData) && isActuallyEmpty(usedData) && isActuallyEmpty(noUsedData) && isActuallyEmpty(excessUsedData))
  )
    return null;
  return labelLayoutBarChartFn(subject, false, unit, xAxisData, specData, usedData, noUsedData, excessUsedData, actuallyUsedData);
};

/**
 * @description:   获取排放echarts配置（气化课、机械课）
 * @param {SubjectType} subject
 * @param {string} unit
 * @param {boolean} flag    false  气化课      true  机械课
 * @return {*}
 */
export const useLabelLayoutEmissionAndRecoveryGWMFn = async (
  subject: SubjectType,
  unit: string = "",
  flag: boolean = false
): Promise<CommonEcharts.CommonEchartsOption> => {
  const params = getParams(subject);
  let res = null;
  if (flag) {
    res = await getFabMachineEmissionAndRecovery(params);
  } else {
    res = await getFabEmissionAndRecovery(params);
  }
  if (!res?.length) return null;
  const { xAxisData, specData, usedData, noUsedData, excessUsedData, actuallyUsedData, recoveryData } = formatEmissionAndRecoveryGWMData(res);
  if (
    isActuallyEmpty(xAxisData) ||
    (isActuallyEmpty(specData) &&
      isActuallyEmpty(usedData) &&
      isActuallyEmpty(noUsedData) &&
      isActuallyEmpty(excessUsedData) &&
      isActuallyEmpty(recoveryData))
  )
    return null;
  if (subject === "WATER" || subject === "MACHINE") {
    return labelLayoutBarChartFn(subject, true, unit, xAxisData, specData, usedData, noUsedData, excessUsedData, actuallyUsedData, recoveryData);
  } else {
    return labelLayoutBarChartFn(subject, true, unit, xAxisData, specData, usedData, noUsedData, excessUsedData, actuallyUsedData);
  }
};

/**
 * @description: 获取总用电量echarts配置（电课）
 * @param {Array} res
 * @return {*}
 */
export const useLabelLayoutElectricityConsumeMEFn = async (unit: string): Promise<CommonEcharts.CommonEchartsOption> => {
  const res = await getFabElectricityConsume();
  if (!res?.length) return null;
  const { xAxisData = [], data = [] } = formatElectricityConsumeData(res);
  if (isActuallyEmpty(xAxisData) || isActuallyEmpty(data)) return null;
  const title = "";
  return useLabelLayoutBarChartFn({}, xAxisData, data, title, unit, "#3B82F6");
};
